<template>
<a-spin tip="Loading..." :spinning="spinning">
    <a-layout style="height:100%;">
        <a-layout-sider :style="pageLayoutSiderStyle">
            <div class="sider-inner" :style="{width:showSide?'100%':'10px'}">
                <div class="switch" @click="switchSider">
                    <a-icon type="backward" v-if="showSide" />
                    <a-icon type="forward" v-else />
                </div>
                <div class="list" v-if="showSide">
                    <a-tree
                        :expanded-keys="expandedKeys"
                        :auto-expand-parent="autoExpandParent"
                        @expand="onExpand"
                        :tree-data="treeData"
                        @select="onSelect"
                        :replaceFields="{children:'children', title:'cubeNameZh', key:'cubeId', value: 'cubeId'}"
                        :selectedKeys="selectedKeys"
                    />
                </div>
            </div>
        </a-layout-sider>
        <a-layout-content>
            <div class="platform">
                <div class="module-name">
                    <div class="name">{{cubeName}}</div>
                </div>
                <div class="platform-layout">
                    <a-layout style="height:100%">
                        <a-layout-header style="height:88px;background:#fff;">
                            <div class="toolbar">
                                <div class="ctrl-btn">
                                    <div class="item" @click="changeEditStatus" :class="{active:editStatus}">
                                        <span class="iconfont icon-bianji1"></span>
                                        <div class="name">编辑</div>
                                    </div>
                                    <div class="item" @click="saveData">
                                        <span class="iconfont icon-baocun"></span>
                                        <div class="name">保存</div>
                                    </div>
                                    
                                    <div class="upload-btn2" v-if="hotRef">
                                        <a-upload
                                            name="file"
                                            :multiple="false"
                                            :action="uploadUrl"
                                            :showUploadList="false"
                                            @change="handleChangeUpload"
                                        >
                                            <div class="item">
                                                <span class="iconfont icon-daoru"></span>
                                                <div class="name">导入</div>
                                            </div>
                                        </a-upload>
                                    </div>

                                    <div class="item" v-else @click="beforeUpload">
                                        <span class="iconfont icon-daoru"></span>
                                        <div class="name">导入</div>
                                    </div>

                                    <div class="item" @click="exportCsv">
                                        <span class="iconfont icon-daochu"></span>
                                        <div class="name">导出</div>
                                    </div>
                                    <div class="item" @click="undo" :class="{'disabled':!hotRef||!hotRef.isUndoAvailable||!hotRef.isUndoAvailable()}">
                                        <span class="iconfont icon-houtui"></span>
                                        <div class="name">上一步</div>
                                    </div>
                                    <div class="item" @click="redo" :class="{'disabled':!hotRef||!hotRef.isRedoAvailable||!hotRef.isRedoAvailable()}">
                                        <span class="iconfont icon-qianjin"></span>
                                        <div class="name">下一步</div>
                                    </div>
                                    <div class="item" @click="refresh">
                                        <span class="iconfont icon-icon_refresh"></span>
                                        <div class="name">刷新</div>
                                    </div>
                                    <div class="item" @click="rotate">
                                        <span class="iconfont icon-hangliezhuanzhi"></span>
                                        <div class="name">行列转置</div>
                                    </div>
                                </div>
                            </div>
                        </a-layout-header>
                        <a-layout style="height:100%">
                            <a-layout-sider :style="{width:'244px',flex:'0 0 244px', maxWidth:'244px',minWidth:'244px', background:'#fff',borderRight:'1px solid #ddd'}">
                                <div class="dim-new-time">
                                    <div class="name">最新时间</div>
                                    <div class="form">
                                        <a-input-number style="width:146px;margin-right:10px; height:32px" v-model="newYear" />
                                        <a-button type="primary" @click="addNewYear">添加</a-button>
                                    </div>
                                </div>
                                <Dimensions :dimData="dimData" :cubeId="cubeId" :sheetId="sheetId" ref="dimensions" @selectDimCode="selectDimCode" @dimensionDragEnd="dimensionDragEnd" :isInput="true" />
                                <div class="sync-btn">
                                    <a-button type="primary" @click="goSync">查询数据</a-button>
                                </div>
                            </a-layout-sider>
                            <a-layout-content style="padding:0 10px;">
                                <div style="widht:100%;height:100%" class="input-data" ref="handsontable" v-show="hotRef"></div>   
                                <div v-show="!hotRef">
                                    <div class="cubeInfo" v-if="cubeInfo">
                                        <dl>
                                            <dt>{{cubeInfo.cubeFnameZh}}</dt>
                                            <dd><div class="label">数据量：</div>{{cubeInfo.totalNum}}<div class="clear"></div></dd>
                                            <dd><div class="label">数据起止时间：</div>{{cubeInfo.startDate}}~{{cubeInfo.lastDate}}<div class="clear"></div></dd>
                                            <dd><div class="label">数据频度：</div><span v-if="cubeInfo.freqId===1">年度</span><span v-if="cubeInfo.freqId===3">季度</span><span v-if="cubeInfo.freqId===4">月度</span><div class="clear"></div></dd>
                                            <dd><div class="label">最新更新时间：</div>{{cubeInfo.lstmodDate}}<div class="clear"></div></dd>
                                        </dl>
                                    </div>
                                </div>                             
                            </a-layout-content>
                        </a-layout>
                    </a-layout>
                </div>
            </div>
        </a-layout-content>
    </a-layout>
</a-spin>
</template>

<script>
import {pageLayoutSiderStyle,pageLayoutSiderHideStyle} from '../../until/global_style';
import 'handsontable/dist/handsontable.full.css';
import Handsontable from 'handsontable'; 
import Dimensions from '../../components/Dimensions.vue';
import {createSettings, tableParse} from '../../until/handsontableSetting';
import { getCookie, messageTips, objToUrl, trim } from '../../until/tools';
import config from '../../until/configs';
import { setCube } from '../../until/data_tools';

export default {
    name:'Cube',
    components:{Dimensions},
    data() {
        return {
            pageLayoutSiderStyle:pageLayoutSiderStyle,
            showSide:true,
            expandedKeys: [],
            autoExpandParent: true,
            treeData:[],
            hotRef:null,
            dimData:null,
            sheetId:null,
            newSheetId:null,
            allDimensions:[],
            cubeInfo:null,
            spinning:false,
            newYear:null,
            editStatus:false,
            tableData:null
        }
    },
    computed:{
        cubeId() {
            let id = this.$route.query.cubeId;
            if(id) {
                return parseInt(id);
            }
            return 0;
        },
        cubeName() {
            let name = this.$route.query.cubeName;
            if(name) {
                return name;
            }
            return null;
        },
        selectedKeys() {
            let cubeId = parseInt(this.$route.query.cubeId);
            return [cubeId];
        },
        uploadUrl() {
            return config.inputsImportFile+'?sid='+getCookie('bd_sid')+'&sheetId='+this.sheetId;
        },
    },
    watch: {
        cubeId(value) {
            this.newSheetId = Math.random();
            this.getDimensions(value);
        }
    },
    methods:{
        switchSider() {
            this.showSide = !this.showSide;
            if(this.showSide) {
                this.pageLayoutSiderStyle = pageLayoutSiderStyle;
            } else {
                this.pageLayoutSiderStyle = pageLayoutSiderHideStyle
            }
            if(this.hotRef) {
                this.resizeTable();
            }
        },

        resizeTable() {
            this.hotRef.destroy();
            let settings = createSettings(this.tableData,this.getIndicotor);
            settings.rowHeaders = true;
            let handsontableDom = this.$refs.handsontable;                
            this.hotRef = new Handsontable(handsontableDom, settings);
            setTimeout(()=>{
                this.hotRef.render();
            },500);
        },

        onExpand(expandedKeys) {
            this.expandedKeys = expandedKeys;
            this.autoExpandParent = false;
        },

        onSelect(selectedKeys, info) {
            if(info.node.dataRef.children&&info.node.dataRef.children.length>0) {
                info.node.onExpand()
                return false;
            } else {
                this.$router.push({
                    path:'/inputs_data',
                    query:{
                        cubeId:info.node.eventKey,
                        cubeName:info.node.dataRef.cubeNameZh
                    }
                })
            }
        },
        beforeUpload() {
            if(!this.hotRef) {
                messageTips('请先生成对应的数据表格',2);
                return false;
            }
        },
        handleChangeUpload({file}) {
            if (file.status === 'done') {
                if(file.response) {
                    let res = file.response;
                    if(res.dataletBO&&res.dataletBO.cellBOs) {
                        messageTips(`${file.name} 上传成功。`,3);
                        let table = tableParse({
                            fixedColumnsLeft: res.dataletBO.metaLefts.length,
                            fixedRowsTop:res.dataletBO.metaTops.length,
                            values:res.dataletBO.cellBOs
                        });
                        this.tableData = table;
                        let settings = createSettings(table);
                        settings.rowHeaders = true;
                        let handsontableDom = this.$refs.handsontable;
                        if(this.hotRef) {
                            this.hotRef.destroy();
                        }
                        this.hotRef = new Handsontable(handsontableDom, settings);

                        setTimeout(()=>{
                            this.hotRef.render();
                        },10)
                    } else {
                        
                        messageTips(res.message,1);
                    }
                    
                }
            } else if (file.status === 'error') {
                messageTips(`${file.name} 上传失败。`,1);
            }
        },

        getTreeList(arr,pid,result) {
            arr.forEach((item)=>{
                item.value = item.cubeId;
                item.key = item.cubeId;
                item.scopedSlots = { title: 'title' };
                item.title = item.cubeNameZh;
                item.titleCopy = item.cubeNameZh;
                if(item.pid===pid) {
                    if(!item.children) {
                        item.children = [];
                    }
                    item.children = this.getTreeList(arr,item.cubeId,item.children);
                    result.push(item);
                }
            });
            return result;
        }, 

        getDimensions(cubeId) {
            this.$http.getDimensions({cubeId,isInput:1}).then(res=>{
                if(res&&res.dataletBO) {
                    let checkedCodes = {};
                    res.dataletBO.allDimensions.dimensionVOList.forEach(item=>{
                        checkedCodes[item.dimensionId] = [];
                    });  
                    this.dimData = {
                        metaLefts:res.dataletBO.metaLefts,
                        metaTops:res.dataletBO.metaTops,
                        allDimensions:res.dataletBO.allDimensions.dimensionVOList,
                        checkedCodes:checkedCodes
                    }
                    this.allDimensions = res.dataletBO.allDimensions.dimensionVOList;
                    this.sheetId = res.dataletBO.sheetId;
                    this.cubeInfo = res.dataletBO.cube;
                    if(this.hotRef) {
                        this.hotRef.destroy();
                        this.hotRef = null;
                    }
                }
            })
        },
        goSync() {
            let params = {
                s1:{empty:'dealStr'},
                s2:{method:'',type:''},
                s3:{index8020:'',fontStyle8020:'',bgColor8020:''},
                s4:{orderStr:'',index:''},
                s5:{dealStr:'',showBackColor:'',showFontStyle:''},
                cubeId:this.cubeId,
                sheetId:this.sheetId,
            }
            if(!this.newSheetId) {
                this.newSheetId = Math.random();
            }
            params.newSheetId = this.newSheetId;
            let dimsCode = this.$refs.dimensions.checkedCodes;
            let dims = [];
            var hasBlankDim = false;
            for(let i in dimsCode) {
                let obj = {codeName:i,codes:dimsCode[i].sort()};
                dims.push(obj);
                if(dimsCode[i].length===0) {
                    hasBlankDim = true;
                }
            }
            if(hasBlankDim) {
                messageTips('所有维度均不得为空',2);
                return false;
            }
            params.dims = JSON.stringify(dims);
            let metaColumns = this.$refs.dimensions.metaLeftsNames;
            let metaRows = this.$refs.dimensions.metaTopsNames;
            let fix = this.$refs.dimensions.fixedsNames;
            if(metaColumns.length===0||metaRows.length===0) {
                messageTips('行或列至少要有一个维度',2);
                return false;
            }
            params.metaColumns = metaColumns.join('-');
            params.metaRows = metaRows.join('-');
            params.fix = fix.join('-');
            this.$http.syncData(params).then(res=>{
                if(!res.dataletBO) {
                    return false;
                }
                let fixedLeft = params.metaColumns.split('-');
                let fixedTop = params.metaRows.split('-');
                let table = tableParse({
                    fixedColumnsLeft: fixedLeft.length,
                    fixedRowsTop:fixedTop.length,
                    values:res.dataletBO.cellBOs
                });
                this.tableData = table;
                let settings = createSettings(table);
                settings.rowHeaders = true;
                let handsontableDom = this.$refs.handsontable;
                if(this.hotRef) {
                    this.hotRef.destroy();
                }
                this.hotRef = new Handsontable(handsontableDom, settings);

                setTimeout(()=>{
                    this.hotRef.render();
                },10)
            })
        },
        saveData() {
            if(!this.hotRef) {
                return false;
            }
            let data = this.hotRef.getData();
            data.forEach(item=>{
                item.forEach(i=>{
                    if(typeof i === 'string') {
                        i = trim(i);
                    }
                })
            })
            
            let params = {
                sheetId:this.sheetId,
                vals:data
            }
            this.$http.saveData(params).then(res=>{
                if(res) {
                    if(res.success) {
                        messageTips(res.message,3);
                        this.editStatus = false;
                        this.goSync();
                    } else {
                        this.$error({
                            title: '提示',
                            content: res.message,
                            centered:true,
                            onOk() {},
                            okText:'确定'
                        });
                    }
                }
            })
        },
        undo() {
            if(!this.hotRef) {
                return false;
            }
            this.hotRef.undo();
        },
        redo() {
            if(!this.hotRef) {
                return false;
            }
            this.hotRef.redo();
        },
        exportCsv() {
            if(!this.hotRef) {
                return false;
            }
            let params = {
                sheetId:this.sheetId,
                sid:getCookie('bd_sid')
            }
            window.location.href = config.downloadData+'?'+objToUrl(params);
        },
        refresh() {
            if(!this.hotRef) {
                return false;
            }
            var that = this;
            this.$confirm({
                title: '提示',
                content: '此操作将会重新查询数据，未保存的数据将会丢失，是否继续？',
                okText:'继续',
                cancelText:'取消',
                centered:true,
                onOk() {
                    that.goSync();
                },
                onCancel() {},
            });
        },
        rotate() {
            if(!this.hotRef) {
                return false;
            }
            let metaLefts = this.$refs.dimensions.metaLeftsNames;
            let dimsCode = this.$refs.dimensions.checkedCodes;
            let rows = 1;
            for(let i in dimsCode) {
                if(metaLefts.indexOf(i)!==-1) {
                    rows = rows*dimsCode[i].length;
                }
            }
            if(rows>255) {
                messageTips('不支持大于255列的数据',2);
                return false;
            }
            var that = this;
            this.$confirm({
                title: '提示',
                content: '此操作将会重新查询数据，未保存的数据将会丢失，是否继续？',
                okText:'继续',
                cancelText:'取消',
                centered:true,
                onOk() {
                    let metaLefts = that.$refs.dimensions.metaLeftsNames;
                    let metaTops = that.$refs.dimensions.metaTopsNames;
                    let fixeds = that.$refs.dimensions.fixedsNames;
                    let dimsCode = that.$refs.dimensions.checkedCodes;
                    if(metaLefts.length===0||metaTops.length===0) {
                        messageTips('行或列至少要有一个维度',2);
                        return false;
                    }
                    that.dimData = {
                        metaLefts:metaTops,
                        metaTops:metaLefts,
                        fixeds:fixeds,
                        allDimensions:that.allDimensions,
                        checkedCodes:dimsCode
                    }
                    setTimeout(()=>{
                        that.goSync();
                    },20);
                },
                onCancel() {},
            });
        },
        addNewYear() {
            if(!this.newYear) {
                return false;
            }
            this.$http.inputs_add_new_year({cubeId:this.cubeId,newTime:this.newYear+'10'}).then(res=>{
                if(res) {
                    if(res.success) {
                        this.getDimensions(this.cubeId);
                        messageTips(res.message,3);
                        this.newYear = null;
                    } else {
                        messageTips(res.message,1);
                    }
                }
            });
        },
        selectDimCode(data) {
            let obj = {...this.dimData};
            obj.checkedCodes = data;
            this.dimData = {...obj};
        },
        dimensionDragEnd(data) {
            this.dimData = data;
        },
        changeEditStatus() {
            if(!this.hotRef) {
                return false;
            }
            this.editStatus = !this.editStatus;
            this.tableData.editable = this.editStatus;
            let settings = createSettings(this.tableData);
            settings.rowHeaders = true;
            let handsontableDom = this.$refs.handsontable;
            if(this.hotRef) {
                this.hotRef.destroy();
            }
            this.hotRef = new Handsontable(handsontableDom, settings);

            setTimeout(()=>{
                this.hotRef.render();
            },10)
        }
    },
    mounted() {
        this.$http.getUserInfo().then(res=>{
            if(res&&res.userInfo&&res.userInfo.metaCubeList) {
                let arr = setCube(res.userInfo.metaCubeList);
                this.treeData = arr;
                if(this.cubeId) {
                    res.userInfo.metaCubeList.some(item=>{
                        if(item.cubeId===this.cubeId) {
                            this.expandedKeys = [item.pid];
                            return true;
                        }
                    });
                }
                
                return res.userInfo.metaCubeList;
            }
        }).then(res=>{
            if(res) {
                let cubeId,cubeName;
                if(res[0].children&&res[0].children[0]) {
                    cubeId = res[0].children[0].cubeId;
                    cubeName = res[0].children[0].cubeNameZh;
                } else {
                    cubeId = res[0].cubeId;
                    cubeName = res[0].cubeNameZh;
                }
                if(!this.$route.query.cubeId) {                    
                    this.expandedKeys = [res[0].cubeId];
                    this.$router.push({path:'/inputs_data',query:{cubeId,cubeName}});
                } else {
                    this.getDimensions(this.$route.query.cubeId)
                }
            }
        });
        window.onresize = ()=>{
            if(this.hotRef) {
                this.resizeTable();
            }
        }
        
    }
}
</script>

<style lang="scss">
    @import '../../scss/platform.scss';
</style>